<template>
  <div class="change-password">
    <mains title="修改密码">
      <template #content>
        <Card style="width: 100%">
          <template #title>
            <div class="title">修改密码</div>
          </template>
          <!-- 表单区域 -->
          <Form
            ref="formValidates"
            :model="formValidate"
            :rules="ruleValidate"
            :label-width="80"
            label-position="left"
          >
            <FormItem label="新密码" prop="password">
              <Input
                v-model="formValidate.password"
                placeholder="请输入新密码"
                style="width: 240px"
                type="password"
              ></Input>
            </FormItem>
            <FormItem label="确认密码" prop="passwdCheck">
              <Input
                v-model="formValidate.passwdCheck"
                placeholder="再次输入新密码"
                style="width: 240px"
                type="password"
              ></Input>
            </FormItem>
            <FormItem>
              <Button
                type="primary"
                size="large"
                style="width: 100px"
                @click="handleSubmit('formValidate')"
                >保存</Button
              >
            </FormItem>
          </Form>
        </Card>
      </template>
    </mains>
  </div>
</template>

<script setup>
import mains from '@/components/main.vue'
import { ref } from 'vue'

const formValidates = ref(null)
let formValidate = ref({
  password: '',
  passwdCheck: '',
})
const validatePass = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请输入密码'))
  } else {
    if (formValidate.value.passwdCheck !== '') {
      // 对第二个密码框单独验证
      formValidates.value.validateField('passwdCheck')
    }
    callback()
  }
}
const validatePassCheck = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请再次输入密码'))
  } else if (value !== formValidate.value.password) {
    callback(new Error('两次密码不一致!'))
  } else {
    callback()
  }
}
const ruleValidate = ref({
  password: [{ validator: validatePass, trigger: 'blur' }],
  passwdCheck: [{ validator: validatePassCheck, trigger: 'blur' }],
})

const handleSubmit = (name) => {
  this.$refs[name].validate((valid) => {
    if (valid) {
      this.$Message.success('Success!')
    } else {
      this.$Message.error('Fail!')
    }
  })
}
</script>

<style scoped>
.change-password {
  :deep(.ivu-card-head) {
    background: #ebeef1;
  }
  .title {
    font-size: 16px;
    font-weight: 800;
    color: #409eff;
  }
}
</style>